package com.weiyi.portal.modules.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weiyi.common.common.api.CommonPage;
import com.weiyi.common.common.api.CommonResult;
import com.weiyi.portal.modules.ums.mapper.UmsChatMessageMapper;
import com.weiyi.portal.modules.ums.model.UmsChatList;
import com.weiyi.portal.modules.ums.model.UmsChatMessage;
import com.weiyi.portal.modules.ums.model.UmsChatUserLink;
import com.weiyi.portal.modules.ums.service.ChatService;
import com.weiyi.portal.modules.ums.service.UmsChatListService;
import com.weiyi.portal.modules.ums.service.UmsChatMessageService;
import com.weiyi.portal.modules.ums.service.UmsChatUserLinkService;
import com.weiyi.portal.dto.ChatListDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service("chatService")
public class ChatServiceImpl implements ChatService {
    @Autowired
    UmsChatUserLinkService umsChatUserLinkService;
    @Autowired
    UmsChatListService umsChatListService;
    @Autowired
    UmsChatMessageService umsChatMessageService;
    @Autowired
    UmsChatMessageMapper umsChatMessageMapper;

    @Override
    public String selectAssociation(String fromUser, String toUser) {
        QueryWrapper<UmsChatUserLink>queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UmsChatUserLink::getFromUser, fromUser).eq(UmsChatUserLink::getToUser, toUser);
        UmsChatUserLink one = umsChatUserLinkService.getOne(queryWrapper);
        if(one==null)return null;
        return one.getLinkId();
    }

    @Override
    public Boolean isFirstChat(String fromUser, String toUser) {
        String LinkedId=selectAssociation(fromUser, toUser);

        if(LinkedId==null){
            //创建聊天关系
            String newId = UUID.randomUUID().toString();
            UmsChatUserLink userLink = new UmsChatUserLink();
            userLink.setLinkId(newId);
            userLink.setFromUser(fromUser);
            userLink.setToUser(toUser);
            umsChatUserLinkService.save(userLink);

            //添加两条聊天列表数据（发送方，接收方）
            UmsChatList fromUserList = new UmsChatList(null,newId, fromUser, toUser, 0, 0, 0,1);
            UmsChatList toUserList = new UmsChatList(null,newId, toUser, fromUser, 0, 0, 0, 1);
            ArrayList<UmsChatList> chatLists = new ArrayList<UmsChatList>();
            chatLists.add(fromUserList);
            chatLists.add(toUserList);
            umsChatListService.saveBatch(chatLists);

            return true;
        }
        return false;
    }

    @Override
    public void saveMessage(UmsChatMessage chatMessage) {
        String linkId = chatMessage.getLinkId();
        String fromUser = chatMessage.getFromUser();
        String toUser = chatMessage.getToUser();

        //将一条的信息的状态（最后一条）改为否
        UpdateWrapper<UmsChatMessage> Wrapper=new UpdateWrapper<>();
        Wrapper.setSql("is_latest = 0");
        Wrapper.lambda().eq(UmsChatMessage::getLinkId, linkId).eq(UmsChatMessage::getIsLatest, 1);
        umsChatMessageService.update(Wrapper);

        //判断聊天双方是否在同一窗口聊天
        int flag = umsChatMessageMapper.selectIsSaveWindows(linkId, fromUser, toUser);
        UpdateWrapper<UmsChatList> queryWrapper=new UpdateWrapper<>();

        
        // 1--只有一方在窗口中 未读数加给接收方，2--两者都在窗口中 清除未读数
        if (flag == 1) {
            //更新未读数
            queryWrapper.setSql("unread=unread+1").lambda().eq(UmsChatList::getLinkId, linkId);
            umsChatListService.update(queryWrapper);
        } else if (flag == 2) {
            //清空所有的未读数
            queryWrapper.setSql("unread=0").lambda().eq(UmsChatList::getLinkId, linkId);
            umsChatListService.update(queryWrapper);
        }
        //暂时将消息全部设置为文本消息
        chatMessage.setType(0);
        //保存聊天记录
        umsChatMessageService.save(chatMessage);
    }

    @Override
    public CommonResult getFromUserChatList(String fromUser) {
        List<ChatListDTO> chatListDTOS = umsChatMessageMapper.selectChatLists(fromUser);
        return CommonResult.success(chatListDTOS);
    }

    @Override
    public CommonPage getRecentChatRecords(String fromUser, String toUser, int pageNum, int pageSize) {
        //获取两者之间的关联id
        String linkId = selectAssociation(fromUser, toUser);

        //查询聊天信息（包括未读）
        //List<ChatMessageData> chatMessageData = umsChatMessageMapper.selectChatMessages(linkId, startIndex, pageSize);
        Page page = new Page(pageNum, pageSize);

        QueryWrapper<UmsChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UmsChatMessage::getLinkId, linkId).orderByDesc(UmsChatMessage::getSendTime);

        //最新的消息位于列表最顶部，前端需要反转一下
        Page result = umsChatMessageService.page(page, queryWrapper);

        //清空未读信息
        UpdateWrapper<UmsChatList> wrapper=new UpdateWrapper<>();
        wrapper.setSql("unread=0").lambda().eq(UmsChatList::getLinkId, linkId);
        umsChatListService.update(wrapper);

        return CommonPage.restPage(result);
    }

    @Override
    public void updateWindows(String fromUser, String toUser) {
        //获取两者之间的关联id
        String linkId = selectAssociation(fromUser, toUser);

        //更新点击了聊天框的同一窗口值

        umsChatMessageMapper.updateIsSaveWindows(linkId, fromUser);

        //清除当前fromUser的未读数
        umsChatMessageMapper.clearUnread(fromUser, toUser, linkId);

        //更新其他窗口的值
        umsChatMessageMapper.updateOtherWindows(linkId, fromUser);
    }

    @Override
    public CommonResult getUnreadTotalNumber(String username) {
        //查询用户的所有的未读数
        Integer unreadTotalNumber = umsChatMessageMapper.selectUnreadTotalNumber(username);

        if (unreadTotalNumber != null) {
            return CommonResult.success(unreadTotalNumber);
        } else {
            return CommonResult.success(0);
        }
    }

    @Override
    public void resetWindows(String username) {
        umsChatMessageMapper.resetWindows(username);
    }
}